package com.nio;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.ServerSocket;
import java.nio.ByteBuffer;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;

public class SocketMain {
    public static void main(String[] args) throws IOException, InterruptedException {
        String abc = "qwedadasdqwvfdfvd";
        int port = 8888;
        ByteBuffer wrap = ByteBuffer.wrap(abc.getBytes());
        // 打开ServerSocketChannel
        ServerSocketChannel ssc = ServerSocketChannel.open();
        // 由于 ServerSocketChannel 没有 bind()方法，因此有必要取出对等的 socket 并使用它来绑定到一个端口以开始监听连接
        ssc.socket().bind(new InetSocketAddress(port));
        // 在非阻塞模式下运行
        ssc.configureBlocking(false);
        // 监听有新连接串入
        while (true){
            // 返回 SocketChannel 类型对象,可以在非阻塞模式下运行
            SocketChannel accept = ssc.accept();
            if(accept == null){ // 没有连接传入
                System.out.println("null");
                Thread.sleep(2000);
            }else{
                System.out.println("连接从:" + accept.socket().getRemoteSocketAddress());
                wrap.rewind(); // 指针0
                accept.write(wrap);
                accept.close();
            }
        }
    }
}
